import React, { useState, useRef, useEffect } from 'react'
import { LuckyWheel } from '@lucky-canvas/react';
import { Button, Toast, Space, Modal, AutoCenter, } from "antd-mobile";
import {LeftOutline} from 'antd-mobile-icons'
import callFeedback from "@/components/common/modalFeedback";
import requewt from "@/utils/requewt";
import { API } from "@/config/api";
import { checkENV2, isValidArr, navigateTo } from "@/utils";
import useRecord from "@/components/pages/stores/useRecord";
import { FeedbackComp } from "@/components/pages/wheel";
import { PrizeComp, RuleComp } from "@/components/common";
import Head from "next/head";
import { BASE_PATH } from "@/config";
import { motion } from 'framer-motion'
import { useToolbar } from '@/components/common/toolbar/useToolbar';
import { checkENV } from '@/utils';
import { useRouter } from 'next/router';

const pageName = "wheel";
const klassName = pageName.replace(/\./g, '-');

function celebrate() {
  const box = document.getElementById(`box`);

  let count = 200;
  let defaults = {
    zIndex: 9999,
    origin: {
      x: 0.5,
      // since they fall down, start a bit higher than random
      y: .5 || 0
    }
  };

  function fire(particleRatio, opts) {
    confetti(
      Object.assign({}, defaults, opts, {
        particleCount: Math.floor(count * particleRatio)
      })
    );
  }

  fire(0.25, {
    spread: 26,
    startVelocity: 55
  });
  fire(0.2, {
    spread: 60
  });
  fire(0.35, {
    spread: 100,
    decay: 0.91,
    scalar: 0.8
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 25,
    decay: 0.92,
    scalar: 1.2
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 45
  });
}

export default function Wheel(props) {
  const {user} = props;

  const {avatar, nickname} = user?.extra || {};
  const {replace} = useRouter()
  const lotterys = useRecord(state => state.lotterys);
  const games = useRecord(state => state.games);
  const update = useRecord(state => state.update);

  const myLucky = useRef();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(undefined);
  const {handleShowPrize} = useToolbar()
  const [blocks] = useState([
    {
      padding: '32px',
      imgs: [{
        src: `${BASE_PATH}/img/wheel/wheel.png`,
        width: '100%',
        height: '100%',
        rotate:true
      }]
    }

  ])
  const [prizes, setPrizes] = useState([])
  const [buttons] = useState([
    {
      radius: '75px',
      fonts: [
        // {
        //   top: '-42px',
        //   // text: `点击\n抽奖`,
        //   // fontStyle: "Changan Uni",
        //   fontSize: `30px`,
        //   fontColor: `#fff`
        // }
      ],
      imgs: [
        {
          src: `${BASE_PATH}/img/wheel/wheel-btn.png`,
          width: '80px',
          height: '88px',
          top: `-75%`
        },

      ],
    }
  ])

  useEffect(() => {
    (async () => {
      await Promise.all([
        await compHandler.fetch(),
        await compHandler.check(),
        
      ])
    })()

    return () => {
      Modal?.clear();
      Toast.clear();
    }
  }, [])
  console.log(lotterys,'lotteryslotteryslotteryslotterys')
  useEffect(() => {
    if (!isValidArr(prizes)) return
    setTimeout(() => {
      myLucky?.current?.init()
    }, 100)
  }, [prizes])
  const onClose = () => {
    setLoading(false)
  }
  const compHandler = {
    // 检测抽奖次数
    check: async () => {
      const resp = await requewt(API.lottery.remain);
    //   const resp = {
    //     "data": {
    //         "pop_share": 1,
    //         "remain_draw_num": 0
    //     },
    //     "error_code": 0,
    //     "msg": "ok",
    //     "request": "GET /warm1118api/gift/draw_num"
    // }
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        return
      }
      if (resp.data?.remain_draw_num === 0) {
        compHandler.userNeedShare(resp.data||0)
      }
      console.log(resp,'resp')
      update(`lotterys`, resp.data);
    },
    // 点击按钮开始抽奖
    gamble: async () => {

      if (lotterys <= 0) {
        
        FeedbackComp({
          item: {
            // draw_icon: `https://yinli-qixi-run.varwey.com/2023_ca/1008/prize-draw.png`,
            category: 99,
          }
        })
        return
      }

      if (loading) return
      Toast.show({content: `请求中`, icon: `loading`})
      setLoading(true);
      const options = {method: `POST`}
      const resp = await requewt(API.lottery.draw, options);
    //   const resp = {
    //     "data": {
    //         "category": 0,
    //         "content": null,
    //         "icon": null,
    //         "id": 8,
    //         "name": "UNI\u4fdd\u6e29\u676f",
    //         "pop_share": 1,
    //         "today_remain_draw_num": 72
    //     },
    //     "error_code": 0,
    //     "msg": "ok",
    //     "request": "POST /warm1118api/gift/draw"
    // }
      console.log(`gamble.resp`, resp);
      setTimeout(() => {
        
        Toast.clear();
      }, 300);

      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        // 特殊的展示方式
        if (resp[`error_code`] === 1001) {
          FeedbackComp({
            item: {
              icon: `https://yinli-qixi-run.varwey.com/2023_ca/1008/prize-draw.png`,
              category: 99,
            }
          })
        } else {
          if(resp.error_code == 999) {
            return  callFeedback({
              hideClose: true,
              closeOnAction: false,
          closeOnMaskClick: false,
          title: <div dangerouslySetInnerHTML={{__html: resp.msg||'游戏失败'}}></div>,
          actions: <Button className="act-btn act-btn-bevel" onClick={async () => {
            const env = checkENV2()
            if (parseInt(resp.error_code) == 999) {
              if (env === 'mini') {
                  wx?.miniProgram.navigateBack && wx?.miniProgram.navigateBack({})
              } else if (env === 'app') {
                if (window.QYApp.closePage) {
                  window?.QYApp?.closePage()
                } else {
                  global?.QYApp.closeView()
                }
              }
            }
          }}>确 定</Button>
            })
          }
          callFeedback({
            title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败!`}}>
            </div>
          })
        }

        return
      }
      const gift = resp.data
      const index = data.findIndex(e => e.name === gift.name);
      // console.log(resp.data)
      // console.log(gift, index)
      if (index < 0) return Toast.show({content: `失败！`})
      setCurrent(resp.data);
      myLucky.current?.play();
      setTimeout(() => {
        console.log(index,'index')
        
        myLucky.current?.stop(index)
        // setLoading(false)
      }, 1000)
    },
    // 展示中奖结果
    percent: (item) => {
      update(`lotterys`, item.today_remain_draw_num);
      FeedbackComp({item, handler: compHandler,onClose})
    },
    // 获取奖品
    fetch: async () => {
      Toast.show({content: `奖品加载中`, icon: `loading`})
      setLoading(true);
      const resp = await requewt(API.prize.entire);
    //   const resp = {
    //     "data": [
         
          
    //       {
    //         "content": null,
    //         "icon": "https://yinli-qixi-run.varwey.com/2023_ca/51_activity/task-da.png",
    //         "id": 3,
    //         "name": "KEEP\u5b63\u5361"
    //     },
    //         {
    //             "content": null,
    //             "icon": "https://yinli-qixi-run.varwey.com/2023_ca/51_activity/task-da.png",
    //             "id": 2,
    //             "name": "KEEP\u6708\u5361"
    //         },
            
            
    //         {
    //           "content": null,
    //           "icon": "https://yinli-qixi-run.varwey.com/2023_ca/51_activity/task-da.png",
    //           "id": 1,
    //           "name": "AIRFOX\u6781\u72d0APP10\u79ef\u5206"
    //       },
    //         {
    //           "content": null,
    //           "icon": "https://yinli-qixi-run.varwey.com/2023_ca/51_activity/task-da.png",
    //           "id": 5,
    //           "name": "\u8c22\u8c22\u53c2\u4e0e"
    //       },
    //       {
    //         "content": null,
    //         "icon": "https://yinli-qixi-run.varwey.com/2023_ca/51_activity/task-da.png",
    //         "id": 4,
    //         "name": "\u6781\u72d0\u5b9a\u5236\u663e\u773c\u5305"
    //     },
          
         
            
    //     ],
    //     "error_code": 0,
    //     "msg": "ok",
    //     "request": "GET /goddess0308api/gift/list"
    // }
      setTimeout(() => {
        setLoading(false);
        Toast.clear();
      }, 800);
      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        return
      }
      compHandler._filterPrize(resp.data)
      setData(resp.data)
    },
    _filterPrize: prs => {
      if (!isValidArr(prs)) return [];
      let _prizes = [];
      prs.forEach((item, i) => {
        let tmp = {
          _id: item.id,
          // background: i === 0 ? `rgb(255, 243, 230)` : i % 2 === 0 ? `rgb(255, 243, 230)` : `#fff`,
          fonts: [
            {
              top: '35%',
              text: '',
              fontStyle: "Changan Uni",
              fontSize: `16px`,
              lengthLimit: `65%`,
              wordWrap: false,
              fontColor: `#3a86e4`
            }
          ],
          imgs: [
            // {
            //   src: item.icon ? item.icon : ``,
            //   width: '25%',
            //   top: '50%'
            // }
          ]
        }
        _prizes.push(tmp);
      })
      setPrizes(_prizes)
    },
    rule: async () => {
      const m = callFeedback({
        bodyClassName: `rule-modal`,
        title: <>星动战队大作战</>,
        content: <div className="inner"><RuleComp /></div>,
        actions: [],
        closeOnAction: true,
        closeOnMaskClick: false,
      })
    },
  }

  return (
    <>
      <Head>
        <title>转盘抽奖</title>
      </Head>
      <div className={`p-${klassName} page page-sec`}>
        <div 
          onClick={() => {
            replace('/landing')
          }}
        style={{
          position: 'fixed',
          left:'3vw',
          top: '2vh',
          fontSize:20,
          color:'#fff',
          zIndex:103
        }}>
        <LeftOutline 
        
        /><span>返回</span>
        </div>
        <div className="inner">
          <div className="position-center">
            <div className="award-pool">

              <div className="award-header">
                <div className="title">
                  <motion.div
                    initial={{opacity:0}}
                    whileInView={{opacity:1}}
                    viewport={{once:true}}
                  >
                    <motion.img
                    // width={'100vw'}
                    style={{width:'53%'}}
                      src={`${BASE_PATH}/img/game/wheel-tips.png`}
                    />
                  </motion.div>
                </div>
              </div>

              <div className="award-wheel">
                {
                  isValidArr(prizes) &&
                  <LuckyWheel ref={myLucky}
                              id={`test`}
                              width="75vw"
                              height="75vw"
                              blocks={blocks}
                              prizes={prizes}
                              buttons={buttons}
                              
                              defaultConfig={{
                                
                                // offsetDegree:348,
                                // stopRange: 2200
                                // gutter:2
                              }}
                              // offsetDegree={200}
                              // stopRange={600}
                              onStart={() => compHandler.gamble()}
                              onEnd={prize => { // 抽奖结束会触发end回调
                                compHandler.percent(current)
                                // callFeedback({title: `恭喜你抽到 ${prize.fonts[0].text} 号奖品`})
                              }}
                  />
                }

              </div>

              <div className="award-footer">
                <div className="remain">您还有（<big>{lotterys}</big>）次抽奖机会</div>
              </div>


              <div className="award-ope">

                <Space className="btn-group mt-3" direction="vertical" >
                  
                  <Button shape={`rounded`} className="act-btn act-btn-bevel"
                          onClick={compHandler.gamble}
                  >
                    立即抽奖
                  </Button>
                  {/* <div style={{marginTop:10}}>
                  <a href='javascript:void(0)' onClick={handleShowPrize}>我的奖品</a>
                  </div> */}
                  {/* <Button shape={`rounded`} className="act-btn act-btn-bevel"
                          onClick={e=>navigateTo(`/landing`)}
                  >
                    返回首页
                  </Button> */}
                </Space>

              </div>
            </div>

          </div>
        </div>

      </div>
    </>
  )
}

Wheel.need2auth = true;
Wheel.pageName = pageName;